<template>
  <div class="authList">
    <el-checkbox v-model="checkAll" @change="handleCheckAll">全选</el-checkbox>
    <div class="check_groups">
      <el-checkbox-group v-for="child in auths" v-model="checkedList" :key="child.aid" class="checkgroup">
        <div class="checkgroup-hd"><el-checkbox :label="child.aid" @change="handleSubCheckAll($event, child)">{{child.name}}</el-checkbox></div>
        <div class="checkgroup-item" v-for="child in child.child" :key="child.aid">
          <div class="checkgroup-hd"><el-checkbox :label="child.aid" @change="handleSubCheckAll($event, child)">{{child.name}}</el-checkbox></div>
          <div class="checkgroup-item">
            <el-checkbox v-for="child in child.child" :key="child.aid" :label="child.aid" @change="ifCheckAll">{{child.name}}</el-checkbox>
          </div>
        </div>
      </el-checkbox-group>
    </div>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        checkAll: false,
        checkedList: []
      }
    },
    mounted () {
      this.init()
    },
    props: ['auths', 'roleAuth'],
    watch: {
      roleAuth: function (cur, old) {
        this.checkedList = []
        this.checkedList = this.checkedList.concat(cur.split(',')).map(x => +x)
      }
    },
    methods: {
      init () {
        if (this.roleAuth) {
          this.checkedList = this.roleAuth.split(',').map(x => +x)
        }
        setTimeout(() => {
          this.ifCheckAll()
        })
      },
      getAllCheck: function (auths) {
        const map = function (auths) { // 递归获取所有选项
          let result = []
          auths.forEach(auth => {
            result.push(auth.aid)
            if (auth.child.length) {
              result = result.concat(map(auth.child))
            }
          })
          return result
        }
        return map(auths)
      },
      handleCheckAll: function (e) {
        this.checkedList = e ? this.getAllCheck(this.auths) : []
      },
      handleSubCheckAll: function (e, auths) {
        const mapDel = (auths) => { // 递归删除子选项
          var index = this.checkedList.indexOf(auths.aid)
          if (index !== -1) {
            this.checkedList.splice(index, 1)
          }
          auths.child.forEach(auth => {
            mapDel(auth)
          })
        }
        mapDel(auths)
        if (e) {
          this.checkedList = this.checkedList.concat(this.getAllCheck([auths]))
        }
        setTimeout(() => {
          this.ifCheckAll()
        })
      },
      ifCheckAll () {
        this.checkAll = document.querySelectorAll('.check_groups .el-checkbox').length === document.querySelectorAll('.check_groups .el-checkbox .is-checked').length
      }
    }
  }
</script>
<style scoped>
  .authList{line-height: 36px}
  .checkgroup>.checkgroup-hd{padding-left:22px;background:#eff2f7;}
  .checkgroup-item{margin-left:22px;padding-left:24px;}
</style>
